package com.wiloon.java8x.thread.deadlock;

/**
 * Created by wiloon on 3/25/17;
 */
class SyncRunnable implements Runnable {
    public boolean flag = false;
    public static Object objA = new Object();
    public static Object objB = new Object();

    public void run() {
        if (flag) {
            while (true) {   //定义为：代码块1
                synchronized (objA) {    //objA锁
                    System.out.println("if objA----");
                    synchronized (objB) {  //objB锁
                        System.out.println("if objB----");
                    }
                }
            }
        } else {
            while (true) {  // 定义为：代码块 2
                synchronized (objB) {   //objB锁
                    System.out.println("else objB----");
                    synchronized (objA) {  //objA锁
                        System.out.println("else objA----");
                    }
                }
            }
        }
    }
}

public class SingleInstance {
    public static void main(String args[]) {
        SyncRunnable sr1 = new SyncRunnable();
        sr1.flag = true;
        SyncRunnable sr2 = new SyncRunnable();
        sr2.flag = false;
        Thread t1 = new Thread(sr1);
        Thread t2 = new Thread(sr2);
        t1.start();
        t2.start();
    }
}